<template>
    <div>
        <el-form ref="form" :model="dish" label-width="80px">
            <el-form-item label="菜品名称">
                <el-input v-model="dish.dishName"></el-input>
            </el-form-item>
            <el-form-item label="所属分类">
                <el-select v-model="dish.categoryId" filterable placeholder="请选择">
                    <el-option v-for="item in categoryList" :key="item.id" :label="item.categoryName" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="价格">
                <el-input type="number" min="0.01" v-model="dish.price"></el-input>
            </el-form-item>
            <el-form-item label="菜品图片">
                <el-upload class="avatar-uploader" action="http://127.0.0.1:8080/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :data="{ scene: 2 }">
                    <img v-if="dish.image" :src="dish.image" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="菜品描述">
                <el-input type="textarea" v-model="dish.description"></el-input>
            </el-form-item>
            <el-form-item label="规格选择">
                <el-select v-model="currentSelectSpecification.id" @change="selectSpecification" filterable
                    placeholder="请选择">
                    <el-option v-for="item in specificationList" :key="item.id" :label="item.specificationName"
                        :value="item.id">
                    </el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-plus" circle @click="addSpecification"></el-button>

                <el-table :data="selectSpecifications" style="width: 50%" max-height="250">
                    <el-table-column fixed prop="id" label="ID">
                    </el-table-column>
                    <el-table-column prop="specificationName" label="规格名称">
                    </el-table-column>
                    <el-table-column prop="dataList" :formatter="dataListFormatter" label="规格项">
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="120">
                        <template slot-scope="scope">
                            <el-button @click.native.prevent="deleteRow(scope.row.id)" type="text" size="small">
                                移除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

            </el-form-item>
            <el-form-item label="排序">
                <el-input type="number" min="0" v-model="dish.sequence"></el-input>
            </el-form-item>
            <el-form-item v-if="is_update" label="状态">
                <el-switch v-model="dish.status" :active-value="1" :inactive-value="0" active-color="#13ce66"
                    inactive-color="#ff4949" :disabled="!is_update">
                </el-switch>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">{{ is_update ? '提交修改' : '立即创建' }}</el-button>
                <el-button @click="backList">返回</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { list } from '@/api/category';
import { specification_list, dish_add, dish_query, dish_update } from '@/api/dish';
import { mapGetters } from 'vuex';
export default {
    //import引入组件才能使用
    components: {},
    props: {
        is_update: Boolean
    },
    data() {
        return {
            dish: {},
            categoryList: [],
            specificationList: [],
            currentSelectSpecification: {},
            selectSpecifications: []
        };
    },
    // 计算属性
    computed: {
        ...mapGetters(['shopId'])
    },
    // 监听data中的数据变化
    watch: {},
    // 方法集合
    methods: {
        handleAvatarSuccess(response) {
            this.dish.image = response.data
            this.$forceUpdate()
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        onSubmit() {
            this.dish.specificationIds = this.selectSpecifications.map(item => item.id)
            if (this.is_update) {
                dish_update(this.dish).then(res => {
                    this.$message.success('更新成功')
                    this.$router.push('/dish/list')
                }).catch(err => {
                    this.$message.error(err || '更新失败')
                })
            } else {
                this.dish.shopId = this.shopId
                dish_add(this.dish).then(res => {
                    this.$message.success('添加成功')
                    this.$router.push('/dish/list')
                }).catch(err => {
                    this.$message.error(err || '添加失败')
                })
            }
        },
        selectSpecification(id) {
            this.currentSelectSpecification = this.specificationList.find(item => item.id == id)
        },
        addSpecification() {
            this.selectSpecifications.push(this.currentSelectSpecification)
        },
        deleteRow(id) {
            this.selectSpecifications = this.selectSpecifications.filter(item => item.id != id)
        },
        dataListFormatter(row, column, cellValue, index) {
            return JSON.parse(row.dataList).join(',')
        },
        backList() {
            this.$router.push('/dish/list')
        }
    },
    // 生命周期，创建完成时（可以访问当前this实例）
    created() {
        let categoryId = this.$route.params.categoryId;
        if (categoryId != 0) {
            this.dish.categoryId = this.$route.params.categoryId
        }
        list().then(res => {
            this.categoryList = res.data
        })
        specification_list().then(res => {
            this.specificationList = res.data
        })
        if (this.is_update) {
            dish_query(this.$route.params.id).then(res => {
                this.dish = res.data
                this.selectSpecifications = res.data.specifications
            }).catch(err => {
                this.$message.error(err || '查询失败')
            })
        }
    },
    // 生命周期：挂载完成时（可以访问DOM元素）
    mounted() {

    },
    beforeCreate() { },//生命周期：创建之前
    beforeMount() { },//生命周期：挂载之前
    beforeUpdate() { },//生命周期：更新之前
    updated() { },//生命周期：更新之后
    beforeDestroy() { },//生命周期：销毁之前
    destroyed() { },//生命周期：销毁完成
    activated() { },//如果页面有keep-alive缓存功能，这个函数会触发执行
}
</script>
<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>